<?php

/**
 * LEAGUEMan
 * 
 * Copyright (C) 2007 Marko Bischof
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

switch ($task) {

    case 'createClubs':

        $database->setQuery("SELECT * FROM jos_leagueman_team WHERE team_club = 0");
        $teams = $database->loadObjectList();

        $total = count($teams);

        $i = 0;
        foreach ($teams AS $team) {
            $club = LM::getLMTable("Club");
            $club->name = $team->team_name;
            if ($club->store()) {
                $database->setQuery(
                    sprintf(
                        "UPDATE jos_leagueman_team SET team_club = %s WHERE team_id = %s",
                        $database->Quote($club->id),
                        $database->Quote($team->team_id)
                    )
                );
                $database->query();
                $i++;
            }
        }

        LM::redirect("teams", "$i clubs added from $total teams");

        break;

    case 'quickadd':

        $row = LM::getLMTable("Team");
        $row->team_name = mosGetParam($_POST, "team_name", "");
        $row->team_name_short = $row->team_name;

        if (!$row->check()) {
            LM::redirect("teams", "Check failed");
        }

        if (!$row->store()) {
            LM::redirect("teams", "Could not save Team");
        }

        LM::redirect("teams", "Team saved successfully");

        break;

    case 'new':
    case 'edit':

        $row = LM::getLMTable("Team");

        if ($task == "edit") {
            $row->load($cid[0]);
        }

        $template = LM::getTemplate();

        $template->assign("view", "admin/form_teams.tpl.php");
        $template->assign("project", $project);
        $template->assign("team", $team);
        $template->assign("my", $my);
        $template->assign("row", $row);
        $template->display("admin/view.tpl.php");
        break;

    case 'bulkadd':

        $template = LM::getTemplate();

        $template->assign("view", "admin/form_teams_bulkadd.tpl.php");
        $template->assign("project", $project);
        $template->assign("team", $team);
        $template->assign("my", $my);
        $template->display("admin/view.tpl.php");
        break;

    case 'bulksave':

        $teamtext = mosGetParam($_POST, "teams", "");
        $lines = explode("\r\n", $teamtext);

        $i = 0;
        foreach ($lines AS $line) {

            if (strpos($line, ",")) {
                list($team_name, $team_name_short) = explode(",", $line);
            } else {
                $team_name = $line;
                $team_name_short = $line;
            }

            $team = LM::getLMTable("Team");
            $team->team_name = trim($team_name);
            $team->team_name_short = trim($team_name_short);

            if (!$team->store()) {
                $i++;
            }
        }

        LM::redirect("teams", "Bulksave finished with $i Errors");

        break;

    case 'assign':

        if ($project != null) {

            if (!$project->isAdmin()) {
                LM::redirect("teams", "You are not authorized for this action");
            }

            $total = count($cid);

            $i = 0;
            foreach ($cid AS $id) {

                $ttable = LM::getLMTable("Teammap");
                $ttable->filterbyProject($project->getID());
                $ttable->filterbyTeam($id);

                if ($ttable->getTotalRows() == 0) {
                    $ttable->teammap_project = $project->getID();
                    $ttable->teammap_team = $id;
                    $ttable->teammap_points = 0;
                    $ttable->teammap_user = 62;
                    $ttable->teammap_info = "";
                    if ($ttable->store()) {
                        $i++;
                    }
                }
            }
        }

        LM::redirect("teams", "$i teams assigned");

        break;

    case 'save':
        $row = LM::getLMTable("Team");
        $row->save($_POST);

        $image = saveImage($mainframe->getCfg("absolute_path") . "/images/stories/leagueman/logos/", "upload", "t{$row->getID()}");

        if ($image) {
            $row->team_logo = $image;
        }

        if ($row->store()) {
            $msg = "OK";
        } else {
            $msg = "Could not save Team";
        }

        LM::redirect("teams", $msg);
        break;

    case 'cancel':
        LM::Redirect("teams");
        break;

    case 'remove':

        if (!$project->isAdmin()) {
            LM::redirect("teams", "You are not authorized for this action");
        }

        $total = count($cid);

        $row = LM::getLMTable("Team");

        $i = 0;
        foreach ($cid AS $id) {
            if ($row->delete($id)) {
                $i++;
            }
        }

        LM::redirect("teams", $i . " from " . $total . " Teams deleted");

        break;

    default:

        $limit      = LM::getSessionValueFromRequest("_{$act}_limit", 'limit', 50);
        $limitstart = LM::getSessionValueFromRequest("_{$act}_limitstart", 'limitstart', 0);
        $search     = LM::getSessionValueFromRequest("_{$act}_search_", 'search', '');
        $search     = $database->getEscaped(trim(strtolower($search)));

        $where = array();
        if ($search) {
            $where[] = "LOWER(t.team_name) LIKE '%$search%' OR LOWER(t.team_name_short) LIKE '%$search%'";
        }

        $database->setQuery(
            "SELECT COUNT(*) FROM #__leagueman_team AS t"
            . (count($where) ? "\nWHERE " . implode(' AND ', $where) : "")
        );

        $total = $database->loadResult();
        $pageNav = LM::getPageNav($total, $limitstart, $limit, 1);

        if ($project instanceof LM_Table_Project) {
            $sql = "SELECT t.*, tm.teammap_team
                      FROM #__leagueman_team AS t
                 LEFT JOIN #__leagueman_teammap AS tm ON tm.teammap_team = t.team_id AND tm.teammap_project = {$project->getID()}"
                 . (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
                " ORDER BY t.team_name
                     LIMIT $pageNav->limitstart, $pageNav->limit";
        } else {
            $sql = "SELECT t.*
                      FROM #__leagueman_team AS t"
                 . (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
                " ORDER BY t.team_name
                     LIMIT $pageNav->limitstart, $pageNav->limit";
        }

        $database->setQuery($sql);
        $rows = $database->loadObjectList();

        $template = LM::getTemplate();
        $template->assign("view", "admin/list_teams.tpl.php");
        $template->assign("project", $project);
        $template->assign("team", $team);
        $template->assign("rows", $rows);
        $template->assign("search", $search);
        $template->assign("pageNav", $pageNav);
        $template->assign("my", $my);

        $template->display("admin/view.tpl.php");
        break;
}